import { Component, OnInit } from '@angular/core';
import { Title } from "@angular/platform-browser";
import { HttpService } from "../../http/http.service";
import { NotifyService } from "../../utils/notify.service";
import { ValidateUtil } from "../../utils/validateutil";
import { Router } from '@angular/router';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.styl']
})
export class RegisterComponent implements OnInit {

  private readonly url: string = "/bas/user/register";
  private readonly defImg: string = "assets/register/flash.png";

  constructor(private titleService: Title, private http: HttpService, private notify: NotifyService, private router: Router) {
  }


  isRegister: boolean = true;
  isButton: boolean = false;
  imgSrc: string = this.defImg;
  formData = {
    // key: '',
    phone: '',
    userName: '',
    pwd: '',
    pwd2: '',
    verifyCode: '',
    companyName: ''
  };
  verifiInfo = {
    phone: { err: false, msg: '' },
    userName: { err: false, msg: '' },
    pwd: { err: false, msg: '' },
    pwd2: { err: false, msg: '' },
    companyName: { err: false, msg: '' },
    verifyCode: { err: false, msg: '' }
  };
  iSecond: number = 0;
  codeBtnName = '获取验证码';
  codeBtnState = true;

  ngOnInit() {
    this.titleService.setTitle("欢迎使用爱波瑞精益制造测评系统");
    // this.setImgSrc();
  }

  onAgree(e) {
    const checkbox = e.target;
    this.isButton = !checkbox.checked;
  }

  onGoto() {
    this.router.navigateByUrl("/login");
  }

  onVerifiInput(name) {
    // 因为注册界面相对独立且量少，再单独加载Message显得累赘
    // 所以文言写死在页面
    let isErr: boolean = false;
    let msg: string = "";
    switch (name) {
      case 'phone':
        if (ValidateUtil.isEmpty(this.formData[name])) {
          isErr = true;
          msg = "请输入手机号码";
        } else if (!ValidateUtil.isMobile(this.formData[name])) {
          isErr = true;
          msg = "手机号码格式不正确";
        }
        break;
      case 'userName':
        if (ValidateUtil.isEmpty(this.formData[name])) {
          isErr = true;
          msg = "请输入姓名";
        }
        break;
      case 'pwd':
        if (ValidateUtil.isEmpty(this.formData[name])) {
          isErr = true;
          msg = "请输入密码";
        } else if (this.formData[name].length < 6) {
          isErr = true;
          msg = "密码长度必须大于6";
        }
        break;
      case 'pwd2':
        if (ValidateUtil.isEmpty(this.formData[name])) {
          isErr = true;
          msg = "请再次输入密码";
        } else if (this.formData[name].length < 6) {
          isErr = true;
          msg = "密码长度必须大于6";
        } else if (ValidateUtil.isEmpty(this.formData['pwd']) == false && this.formData[name] != this.formData['pwd']) {
          isErr = true;
          msg = "两次密码输入必须一样";
        }
        break;
      case 'companyName':
        if (ValidateUtil.isEmpty(this.formData[name])) {
          isErr = true;
          msg = "请输入公司名称，且必须包含所在省市";
        }
        break;
      case 'verifyCode':
        if (ValidateUtil.isEmpty(this.formData[name])) {
          isErr = true;
          msg = "请输入验证码";
        } else if (this.formData[name].length != 6) {
          isErr = true;
          msg = "验证码仅能输入6位";
        }
        break;
    }
    this.verifiInfo[name].err = isErr;
    this.verifiInfo[name].msg = msg;
  }

  // 改为短信验证后，不再需要此方法
  // setImgSrc() {
  //   this.http.getNoToken(`${this.url}`, null).subscribe(res => {
  //     if (res.err == '0') {
  //       let imgData = `data:image/png;base64,${res.data.img}`;
  //       this.formData.key = res.data.key;
  //       this.imgSrc = imgData;
  //     } else {
  //       this.imgSrc = this.defImg;
  //       this.formData.key = '';
  //       this.notify.error(res.errMsg).subscribe();
  //     }
  //   });
  // }
  //
  // changeCode() {
  //   this.setImgSrc();
  // }

  onSave() {
    let isAll: boolean = true;
    // if (ValidateUtil.isEmpty(this.formData.key)) {
    //   this.verifiInfo['verifyCode'].err = true;
    //   this.verifiInfo['verifyCode'].msg = '验证码错误，请刷新';
    //   return;
    // }
    this.onVerifiInput('phone');
    this.onVerifiInput('userName');
    this.onVerifiInput('pwd');
    this.onVerifiInput('pwd2');
    this.onVerifiInput('companyName');
    this.onVerifiInput('verifyCode');
    for (let x in this.verifiInfo) {
      if (this.verifiInfo[x].err == true) {
        isAll = false;
        break;
      }
    }
    if (isAll === false) {
      return;
    }
    this.http.postNoToken(this.url, this.formData).subscribe(res => {
      if (res.err == '0') {
        if (res.data && res.data.code != "0") {
          this.verifiInfo[res.data.name].err = true;
          this.verifiInfo[res.data.name].msg = res.data.msg;
          // this.setImgSrc();
        } else {
          this.isRegister = false;
          this.iSecond = 10;
          let stop = setInterval(() => {
            this.iSecond--;
            if (this.iSecond <= 0) {
              clearInterval(stop);
              this.onGoto();
            }
          }, 1000);
        }
      } else {
        // this.setImgSrc();
        this.notify.error(res.errMsg).subscribe();
      }
    });
  }

  // 获取短信验证码
  getVerificationCode() {
    if (ValidateUtil.isEmpty(this.formData.phone)) {
      this.notify.error('请输入手机号码').subscribe();
      return;
    } else if (!ValidateUtil.isMobile(this.formData.phone)) {
      this.notify.error('手机号码格式不正确').subscribe();
      return;
    }

    this.codeBtnState = false;
    this.http.getNoToken('bas/wx/send', { phone: this.formData.phone }).subscribe(res => {
      if (res.err == "0") {
        this.notify.success('验证码已发送').subscribe();
        // 倒计时60秒
        let maxTime = 60;
        let hnd = setInterval(() => {
          maxTime = maxTime - 1;
          this.codeBtnName = maxTime + '秒后再重试';
          if (maxTime <= 0) {
            this.codeBtnState = true;
            this.codeBtnName = '获取验证码';
            clearInterval(hnd);
          }
        }, 1000);
      } else {
        this.notify.error(res.errMsg).subscribe(() => {
          this.codeBtnState = true;
        });
      }
    });
  }

}
